package com.icinfo.cloud.provider.common.utils;

import com.icinfo.framework.tools.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解析变量参数工具类
 *
 * @author shishengyao
 * @description
 * @date 2022/2/26
 */
public class ParseTextUtil {
    private static String PATTERN = "\\$\\{(.*?)}";

    /**
     * 根据正则表达式获取文本中的变量名列表
     *
     * @param content
     * @return {@link List<String> }
     * @author shishengyao
     * @date 2022/02/26
     */
    public static List<String> getParams(String content) {
        Pattern p = Pattern.compile(PATTERN);
        Matcher m = p.matcher(content);
        List<String> result = new ArrayList<String>();
        while (m.find()) {
            result.add(m.group(1));
        }
        return result;
    }

    /**
     * 根据正则表达式将文本中的变量使用实际的数据替换成无变量的文本( ${} )
     *
     * @param content
     * @param dataMap
     * @return {@link String }
     * @author shishengyao
     * @date 2022/02/26
     */
    public static String parseText(String content, Map<String, String> dataMap) {
         String resultText=content;
        Pattern p = Pattern.compile(PATTERN);
        Matcher m = p.matcher(content);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
                String key = m.group(1);
                String value=null;
                if (dataMap !=null && dataMap.size()>0){
                 value = dataMap.get(key);
                 // 处理特殊字符\和$
                 m.appendReplacement(sb, StringUtils.isEmpty(value) ? "" : Matcher.quoteReplacement(value));
                }else {
                    m.appendReplacement(sb,"" );
                }
        }
        m.appendTail(sb);
        resultText= sb.toString();
        return resultText ;
    }
}
